package org.xzx.shop_api.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xzx.shop_api.entity.Address;
import org.xzx.shop_api.mapper.AddressMapper;
import org.xzx.shop_api.mapper.UserMapper;
import org.xzx.shop_api.service.AddressService;
import org.xzx.shop_api.utils.JsonResult;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public JsonResult addAddress(Address address) {
        // 检查是否要设置为默认地址
        Optional.ofNullable(address.getIsDefault())
                .filter(value -> value == 1)
                .ifPresent(value -> {
                    // 如果是默认地址，则取消其他默认地址
                    addressMapper.cancelOtherDefault(address.getUserId());
                });

        int result = addressMapper.insert(address);
        if (result > 0) {
            return JsonResult.success("添加成功", null);
        } else {
            return JsonResult.failed("添加失败");
        }
    }

    @Override
    public JsonResult listAllAddress(int userId) {
        List<Address> address = addressMapper.selectByUserId(userId);
        return JsonResult.success("查询成功", address);
    }

    @Override
    public JsonResult getAddressDetail(int id) {
        Address address = addressMapper.selectById(id);
        if (address == null) {
            return JsonResult.failed("地址不存在");
        }
        return JsonResult.success("查询成功", address);
    }

    @Override
    public JsonResult updateAddress(Address address) {
        // 检查是否要设置为默认地址，先取消其他的默认地址
        Optional.ofNullable(address.getIsDefault())
                .filter(value -> value == 1)
                .ifPresent(value -> addressMapper.cancelOtherDefault(address.getUserId()));
        int result = addressMapper.update(address);
        if (result > 0) {
            return JsonResult.success("更新成功", null);
        } else {
            return JsonResult.failed("更新失败");
        }
    }

    @Override
    public JsonResult deleteAddress(int id, Integer userId) {
        // 获取地址信息确认归属关系
        Address address = addressMapper.selectById(id);
        if (address == null || !Objects.equals(address.getUserId(), userId)) {
            return JsonResult.failed("地址不存在或权限不足");
        }

        // 不能删除默认地址
        Optional.ofNullable(address.getIsDefault())
                .filter(value -> value == 1)
                .ifPresent(value -> JsonResult.failed("默认地址不能删除"));

        int result = addressMapper.delete(id);
        if (result > 0) {
            return JsonResult.success("删除成功", null);
        } else {
            return JsonResult.failed("删除失败");
        }
    }

    @Override
    public List<Address> getAddressesWithUser(int userId) {
        return addressMapper.selectWithUser(userId);
    }
}
